package com.tz.online.user.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tz.online.entity.User;
import com.tz.online.user.service.IUserService;
import com.tz.online.util.BeanFactory;

/**
 * 接收用户登录请求
 * @author Administrator
 */
@WebServlet(name="loginAction",urlPatterns="/user/login")
public class LoginAction extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3108385297838388675L;
	IUserService us = (IUserService) BeanFactory.getBean("userService");
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//接收用户名和密码
		String name = req.getParameter("username");
		String pass = req.getParameter("password");
		String ck = req.getParameter("terms");
		//判断用户是否存在
		User user = us.loginUser(name);
		if(user != null){
			if(user.getPassword().equals(pass)){
				//如果勾选了记住密码，则将用户密码保存进Cookie	
				if ("1".equals(ck)) {
					Cookie c = new Cookie("username",name);
				    Cookie c1 = new Cookie("password",pass);
					c.setMaxAge(2 * 7 * 24 * 60 * 60);
					c.setPath("/");
					c1.setMaxAge(2 * 7 * 24 * 60 * 60);
					c1.setPath("/");
					resp.addCookie(c);
					resp.addCookie(c1);
				}
				//登录成功，把用户对象存入session
				req.getSession().setAttribute("userInfo", user);
				resp.sendRedirect(req.getContextPath()+"/book/IndexAction");
			}else {
				resp.sendRedirect(req.getContextPath()+"/jsp/user/login.jsp?info=1"); //密码错误
			}
		}else {
			resp.sendRedirect(req.getContextPath()+"/jsp/user/login.jsp?info=0");//用户名错误
		}
	}
}
